package com.jinwei.qunguanjia.common.utils;


import com.jinwei.qunguanjia.common.core.domain.model.Condition;
import com.jinwei.qunguanjia.common.enums.WrapperTypeEnum;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ConditionUtils {
    public static <T> List<Condition> add(T t) throws IllegalAccessException {
        List<Condition> conditionList = new ArrayList<>();
        Field [] fields = ArrayUtils.addAll(t.getClass().getDeclaredFields(), t.getClass().getSuperclass().getDeclaredFields());
        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldType = field.getType();
            if (String.class == fieldType || Integer.class == fieldType) {
                Object value = field.get(t);
                if (null != value && "" != value) {
                    Condition condition = new Condition();
                    condition.setColumn(field.getName());
                    if (String.class == fieldType && value.toString().contains(":")) {
                        String type = value.toString().split(":")[0];
                        condition.setType(type);
                        condition.setValue(value.toString().split(":")[1]);
                        conditionList.add(condition);
                    } else {
                        condition.setType(WrapperTypeEnum.EQUAL.getType());
                        condition.setValue(value.toString());
                        conditionList.add(condition);
                    }

                }
            } else if (Map.class == fieldType) {
                Map map = (Map) field.get(t);
                if (map != null && map.size() > 0 && map.containsKey("beginTime")) {
                    Condition condition = new Condition();
                    condition.setColumn("create_time");
                    condition.setType(WrapperTypeEnum.GREATER_THAN_OR_EQUAL_DATE.getType());
                    condition.setValue(map.get("beginTime").toString());
                } else if (map != null && map.size() > 0 && map.containsKey("endTime")) {
                    Condition condition = new Condition();
                    condition.setColumn("create_time");
                    condition.setType(WrapperTypeEnum.LESS_THAN_OR_EQUAL_DATE.getType());
                    condition.setValue(map.get("endTime").toString());
                }
            }
        }
        return conditionList;
    }
}
